package org.dant.ant.extension.net.processors;

import java.io.*;
import java.util.*;

public class ErrorChecker implements Runnable {

  private InputStream stderr;
  private CheckThread checker;

  protected List expectStream = new ArrayList();
  protected boolean finished = true;
  protected StringBuffer errBuffer = new StringBuffer();

  public ErrorChecker(CheckThread checker) {
    this.checker = checker;
  }

  public void run() {
    try {
      System.out.println("std.err checker started");
      checkStdError();
      System.out.println("std.err checker finished");
    } catch (IOException ioe) {
      checker.setSucceed(false);
      ioe.printStackTrace();
    }
  }

  public void addExpectStream(String err) {
    expectStream.add(err);
  }

  public void setProcessErrorStream(InputStream is) {
    this.stderr = is;
  }

  public boolean isFinished() {
    return this.finished;
  }

  public void checkStdError() throws IOException {
    if (stderr == null) {
      System.out.println("standard error is null, finished processing");
      return;
    }
    
    InputStreamReader isr = new InputStreamReader(stderr);
    BufferedReader br = new BufferedReader (isr);
    String s = br.readLine ();
    while(s != null) {
      errBuffer.append(s);
      errBuffer.append("\n");
      
      System.err.println("err line- " + s);

      if (finished && assertExpected(s)) {
        finished = false;
        checker.notifyExe();
        System.out.println("expected std.err string <" + s + ">  occurs, notify the executor, and return back to the client");
      }
      s = br.readLine();
    }

    stderr.close();
  }

  public StringBuffer getErrorBuffer() {
    return this.errBuffer;
  }

  public boolean assertExpected(String line) {
    for(Iterator iter=expectStream.iterator(); iter.hasNext();) {
      String expect = (String) iter.next();
      if (line.indexOf(expect) != -1) {
        return true;
      }
    }
    return false;
  }
}
